package sz.szsmk.citizencard.retrofitrxjava.newversion

import android.util.Log
import com.youzan.androidsdk.YouzanSDK
import org.greenrobot.eventbus.EventBus
import retrofit2.adapter.rxjava.HttpException
import rx.Subscriber
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.model.network.bean.response.BaseBean
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent
import sz.szsmk.citizencard.ui.newversion.bean.AuthRes
import sz.szsmk.citizencard.util.ACache
import sz.szsmk.citizencard.util.Constant
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.text.ParseException

/**
 *  author : hyt
 *  date : 2020/5/8
 *  description :
 */
  class SubscriberCallBack<T>(var apiCallback: ApiCallback<T>) : Subscriber<T>() {

    override fun onNext(t: T) {

        t as BaseBean

        if ("000000" == t.code || "0000" == t.code||"00000" ==t.code) {
            apiCallback.onSuccess(t)
        } else if ("000001" == t.code || "000008" == t.code) {
            //  渠道编码不存在    系统返回异常
            apiCallback.onSuccess(t)
        } else if ( "000016" == t.code ||"000003" == t.code|| "000003" == t.code || "000004" == t.code || "000002" == t.code) {
            //用户在其他终端登录     过期          1002  电子市民卡过期
            //token 异常
            ACache.get(DaggerApplication.getIns()).remove("userinfo")
            ACache.get(DaggerApplication.getIns()).remove("access_token")
            Constant.EXTENT = ""
            ACache.get(DaggerApplication.getIns()).remove("mextend")
            ACache.get(DaggerApplication.getIns()).remove("userId")
            YouzanSDK.userLogout(DaggerApplication.getIns())

            //发消息到 MainActivity token过期  提示重新登录
            val message = MessageEvent(MessageEvent.CODE_TOKEN_ERROR)
            EventBus.getDefault().post(message)


            //退出登陆，用户主动退出登陆状态的时候，可以通过该接口和 SDK 同步登陆状态
//            TransitUI.logout()
//            onFailure(t)
        }else {
            onFailure(t)
        }
    }

    fun onFailure(t: T){
        apiCallback.onFailure(t as BaseBean, Throwable())
    }

    override fun onError(e: Throwable?) {
        var baseBean = BaseBean()

        e?.printStackTrace()

        if(e is ConnectException){
            //这里 通常是 没网 或者 服务没开
            baseBean.message = "网络连接异常"
            apiCallback.onFailure(baseBean, Throwable())
        }else if(e is SocketTimeoutException){
            baseBean.message = "网络连接异常"
            apiCallback.onFailure(baseBean, Throwable())
        } else if(e is HttpException){
            e?.printStackTrace()
            Log.i("onError", "未知错误")
            baseBean.message = "网络连接异常"
            apiCallback.onFailure(baseBean, Throwable())
        }else{
            e?.printStackTrace()
            Log.i("onError", "未知错误")
        }
    }

    override fun onCompleted() {

    }



}